package cn.bby.tools.actions.str.decode;

import cn.bby.tools.actions.str.BaseStringProcessAction;
import com.intellij.openapi.actionSystem.AnActionEvent;

/**
 * Unicode解码Action
 *
 * @author lingma
 * @since 2025/11/7
 */
public class DecodeUnicodeAction extends BaseStringProcessAction {
    @Override
    public String process(AnActionEvent event, String selectedText) {
        try {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            while (i < selectedText.length()) {
                if (i < selectedText.length() - 5 && selectedText.charAt(i) == '\\' && selectedText.charAt(i + 1) == 'u') {
                    try {
                        String hexCode = selectedText.substring(i + 2, i + 6);
                        char unicodeChar = (char) Integer.parseInt(hexCode, 16);
                        sb.append(unicodeChar);
                        i += 6;
                    } catch (NumberFormatException e) {
                        sb.append(selectedText.charAt(i));
                        i++;
                    }
                } else {
                    sb.append(selectedText.charAt(i));
                    i++;
                }
            }
            return sb.toString();
        } catch (Exception e) {
            return selectedText;
        }
    }
}